package com.chattingroom.mqcosumer.service;

import com.rabbitmq.ChattingRoom.util.common.req.HistoryMSGReq;
import com.rabbitmq.ChattingRoom.util.utils.JSONUtil;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * WebSocket service
 * 主要针对单个聊天室进行创建
 * @author SHTL
 */
@ServerEndpoint("/websocket/room/{sid}")
@Component
public class WebSocketServer {
    static Log log = LogFactory.getLog(WebSocketServer.class);

    private static int onlineCount = 0;

    private static CopyOnWriteArrayList<WebSocketServer> webSocketSet = new CopyOnWriteArrayList<WebSocketServer>();

    private Session session;
    private String sid ="";

    /**
     * 连接建立成功调用方法
     * @param session
     * @param sid
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        log.info("有新窗口开始监听:" + sid + "，当前在线人数为:" + getOnlineCount());
        this.sid = sid;
        try {
            sendMessage(JSONUtil.stringify(new HistoryMSGReq()));
        }catch (IOException e) {
            log.error("websocket IO 异常!");
        }
    }

    /**
     * 关闭链接方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("有一连接关闭，当前在线人数为:" + getOnlineCount());
    }

    /**
     * 接受消息
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message,Session session) {
        log.info("收到来自窗口" + sid + "的消息:" + message);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static void sendInfo(String message,@PathParam("sid") String sid) {
        log.info("推送消息到窗口:" + sid + "，推送内容:" + message);
        for (WebSocketServer item:webSocketSet) {
            try {
                if(sid == null) {
                    item.sendMessage(message);;
                }else if(item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            }catch (IOException e) {
                continue;
            }
        }
    }

    @OnError
    public void onError(Session session,Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }


    public static synchronized  int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
